package com.authine.cloudpivot.ext.workflowevent;


import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.utils.BigDecimalUtils;
import com.authine.cloudpivot.ext.utils.FinancialCalculationUtils;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.hermes.app.flow.engine.delegate.event.EventType;
import com.authine.hermes.app.flow.engine.delegate.event.WorkflowEvent;
import com.authine.hermes.app.flow.engine.delegate.event.impl.FlowActivityEventImpl;
import com.authine.hermes.app.flow.engine.delegate.event.impl.WorkItemEventImpl;
import com.authine.hermes.app.flow.engine.impl.persistence.entity.WorkItemEntity;
import com.authine.hermes.app.flow.runtime.engine.listener.AbstractWorkflowEventListener;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.jdbc.core.JdbcTemplate;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
//@Component(value="MyWorkflowEventListener")
public class MyWorkflowEventListener extends AbstractWorkflowEventListener {

    private final JdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(JdbcTemplate.class);

    @Override
    public void onEvent(WorkflowEvent workflowEvent) {
        log.info("----------------------------------------------------");
        log.info("流程code:{},流程id:{},variables:{}",workflowEvent.getWorkflowCode(),workflowEvent.getWorkflowInstanceId(),workflowEvent.getVariables());
        log.info("----------------------------------------------------");
        EventType eventType = workflowEvent.getType();
        if(EventType.WF_START == eventType) {
            log.info("####################################################");
            log.info("####### 1. 流程开始了");
        }

        if(EventType.WF_END == eventType) {
            log.info("####################################################WF_END流程结束处理");
            String bizObjectId=this.getFlowInstanceEntityById(workflowEvent.getWorkflowInstanceId()).getBizObjectId();
            if ("calibration_approval_flow".equals(workflowEvent.getWorkflowCode())){
                int update = JdbcTemplateUtils.builder(ModelConst.T_GOODS_PURCHASE).putFieldAndVal("if_approval", 1)
                        .eq("id", bizObjectId)
                        .update();
                log.info("####### 定标审批结束处理update::{}",update);
            }
            if ("goodsPriceFlow".equals(workflowEvent.getWorkflowCode())){
                log.info("####### 商品调节审批结束处理");
                Map<String, Object> goodsPriceFlowPriceMap= JdbcTemplateUtils.builder(ModelConst.GOODS_PRICE_FLOW).selectField("*")
                        .eq("id", bizObjectId).queryForMap();
                String purchaseId=goodsPriceFlowPriceMap.get("purchase_id").toString();
                BigDecimal newPrice= BigDecimalUtils.isNull(goodsPriceFlowPriceMap.get("goodsPriceFlowPrice"));
                Map<String, Object> goodsPirchaseMap = JdbcTemplateUtils.builder(ModelConst.T_GOODS_PURCHASE).selectField("*")
                        .eq("id", purchaseId).queryForMap();
                BigDecimal num= BigDecimalUtils.isNull(goodsPirchaseMap.get("num"));
                BigDecimal taxRate= BigDecimalUtils.isNull(goodsPirchaseMap.get("tax_rate"));
                BigDecimal taxRateFreight= BigDecimalUtils.isNull(goodsPirchaseMap.get("tax_rate_freight"));
                BigDecimal pretaxFreight= BigDecimalUtils.isNull(goodsPirchaseMap.get("pretax_freight"));
                BigDecimal pretaxPrice = BigDecimalUtils.calculateTaxBefore(newPrice, taxRate);
                BigDecimal pretaxTotal = FinancialCalculationUtils.calculatePretaxTotalByPretaxPrice(pretaxPrice, num);
                BigDecimal total = FinancialCalculationUtils.calculateTotalByPretaxPrice(pretaxPrice, taxRate, num);;
                BigDecimal amount = FinancialCalculationUtils.calculateAmountByPretaxPriceAndPretaxFreight(pretaxPrice, pretaxFreight, taxRate, taxRateFreight, num);
//                BigDecimal taxPayable = FinancialCalculationUtils.calculateTaxPayableByPretaxPrice(pretaxPrice, taxRate, num);
                BigDecimal pretaxAmount = FinancialCalculationUtils.calculatePretaxAmountByPretaxPriceAndPretaxFreight(pretaxPrice, pretaxFreight, num);
//                BigDecimal freight = FinancialCalculationUtils.calculateFreightByPretaxFreight(pretaxPrice, taxRateFreight);
//                BigDecimal taxPayableFreight = FinancialCalculationUtils.calculatePayableFreightByPretaxFreight(pretaxPrice, taxRateFreight);
                int update = JdbcTemplateUtils.builder(ModelConst.T_GOODS_PURCHASE).putFieldAndVal("pretax_total", pretaxTotal)
                        .putFieldAndVal("total", total)
                        .putFieldAndVal("amount", amount)
//                        .putFieldAndVal("tax_payable", taxPayable)
                        .putFieldAndVal("pretax_amount", pretaxAmount)
                        .putFieldAndVal("price", newPrice)
                        .putFieldAndVal("pretax_price", pretaxPrice)
//                        .putFieldAndVal("freight", freight)
//                        .putFieldAndVal("tax_payable_freight", taxPayableFreight)
                        .eq("id", purchaseId)
                        .update();
                log.info("商品调节审批结束处理update::{}",update);
            }
            log.info("####### 2. 流程结束了");
        }

        if(EventType.WF_ABORT == eventType) {
            log.info("####################################################");
            log.info("####### 3. 流程作废了");
        }

        if(EventType.WF_ACTIVATE == eventType) {
            log.info("####################################################");
            log.info("####### 4. 流程激活后");
        }

        if(EventType.ACTIVITY_ACTIVATED == eventType) {
            FlowActivityEventImpl activityEvent = (FlowActivityEventImpl) workflowEvent;
            log.info("####################################################");
            log.info("####### 5. 活动激活后,活动code：{}",activityEvent.getActivityCode());
        }

        if(EventType.ACTIVITY_ACTIVATING == eventType) {
            FlowActivityEventImpl activityEvent = (FlowActivityEventImpl) workflowEvent;
            log.info("####################################################");
            log.info("####### 6. 活动激活前,活动code：{}",activityEvent.getActivityCode());
        }

        if(EventType.ACTIVITY_FINISHED == eventType) {
            FlowActivityEventImpl workItemEntity = (FlowActivityEventImpl) workflowEvent;
            log.info("####################################################活动完成了::活动code{}",workItemEntity.getActivityCode());
            StringBuilder sql = new StringBuilder("select * from commoditymaterials.h_biz_comment where workflowInstanceId='"+workflowEvent.getWorkflowInstanceId()+"' and activityCode='"+workItemEntity.getActivityCode()+"' ORDER BY createdTime desc");
            String commentContent = null;
            if (workItemEntity.getActivityCode().equals("Activity3")){
                List<Map<String, Object>> commentList = jdbcTemplate.queryForList(sql.toString());
                if (CollectionUtils.isNotEmpty(commentList)){
                    commentContent=commentList.get(0).get("content").toString();
                }
                log.info("############commentContent::{}",commentContent);
                String bizObjectId = this.getFlowInstanceEntityById(workflowEvent.getWorkflowInstanceId()).getBizObjectId();
                log.info("############bizObjectId::{}",bizObjectId);
                String costCenterId = JdbcTemplateUtils.builder(ModelConst.T_GOODS_PURCHASE).selectField("cost_center_id")
                        .eq("id", bizObjectId)
                        .queryForPOJO(String.class);
                log.info("############costCenterId::{}",costCenterId);
                StringBuilder updateSql = new StringBuilder("update operation1center.i_operation1center_t_cost_center set name='"+commentContent+"' where id='"+costCenterId+"'");
                jdbcTemplate.update(updateSql.toString());
            }
            if (workItemEntity.getActivityCode().equals("Activity5")){
                List<Map<String, Object>> commentList = jdbcTemplate.queryForList(sql.toString());
                if (CollectionUtils.isNotEmpty(commentList)){
                    commentContent=commentList.get(0).get("content").toString();
                }
                log.info("############commentContent::{}",commentContent);
                String bizObjectId = this.getFlowInstanceEntityById(workItemEntity.getWorkflowInstanceId()).getBizObjectId();
                log.info("############bizObjectId::{}",bizObjectId);
                int update = JdbcTemplateUtils.builder(ModelConst.T_GOODS_PURCHASE).putFieldAndVal("client_purchase_request", commentContent)
                        .eq("id", bizObjectId)
                        .update();
            }

            log.info("####### 7. 活动完成了,活动code：{}", workItemEntity.getActivityCode());
        }

        if(EventType.ACTIVITY_CANCELED == eventType) {
            FlowActivityEventImpl activityEvent = (FlowActivityEventImpl) workflowEvent;
            log.info("####################################################");
            log.info("####### 8. 活动取消了,活动code：{}",activityEvent.getActivityCode());
        }

        if(EventType.ENTITY_CREATED == eventType) {
            log.info("####################################################");
            log.info("####### 9. 创建了1个待办任务");
        }

        if(EventType.ENTITY_UPDATED == eventType) {
            log.info("####################################################修改实体");
            log.info("####### 10. 更新了1个待办任务");
        }

        if(EventType.ENTITY_DELETED == eventType) {
            log.info("####################################################");
            log.info("####### 11. 删除了1个待办任务");
        }

        if(EventType.WORKITEM_SUBMITTED == eventType) {
            //未打印日志
            WorkItemEventImpl workItemEvent = (WorkItemEventImpl) workflowEvent;
            log.info("####################################################");
            WorkItemEntity workItemEntity = workItemEvent.getWorkItemEntity();
            log.info("####### 12. 任务提交后,活动code：{},处理人:{},BOId:{}",workItemEntity.getActivityCode(),
                    workItemEntity.getParticipant()+"-"+workItemEntity.getParticipantName(),
                    this.getFlowInstanceEntityById(workItemEvent.getWorkflowInstanceId()).getBizObjectId());
            log.info("*************************************************");

//            StringBuilder sql = new StringBuilder("select * from commoditymaterials.h_biz_comment where workflowInstanceId="+workflowEvent.getWorkflowInstanceId()+" and activityCode="+workItemEntity.getActivityCode()+" ORDER BY createdTime desc");
//            String commentContent = null;
//            if (workItemEntity.getActivityCode().equals("Activity3")){
//                List<Map<String, Object>> commentList = jdbcTemplate.queryForList(sql.toString());
//                if (CollectionUtils.isNotEmpty(commentList)){
//                    commentContent=commentList.get(0).get("content").toString();
//                }
//                log.info("############commentContent::{}",commentContent);
//                String bizObjectId = this.getFlowInstanceEntityById(workflowEvent.getWorkflowInstanceId()).getBizObjectId();
//                log.info("############bizObjectId::{}",bizObjectId);
//                String costCenterId = JdbcTemplateUtils.builder(ModelConst.T_GOODS_PURCHASE).selectField("cost_center_id")
//                        .eq("id", bizObjectId)
//                        .queryForPOJO(String.class);
//                log.info("############costCenterId::{}",costCenterId);
//                int update = JdbcTemplateUtils.builder(ModelConst.T_COST_CENTER).putFieldAndVal("name", commentContent)
//                        .eq("id", costCenterId)
//                        .update();
//            }
//            if (workItemEvent.getActivityCode().equals("Activity5")){
//                List<Map<String, Object>> commentList = jdbcTemplate.queryForList(sql.toString());
//                if (CollectionUtils.isNotEmpty(commentList)){
//                    commentContent=commentList.get(0).get("content").toString();
//                }
//                log.info("############commentContent::{}",commentContent);
//                String bizObjectId = this.getFlowInstanceEntityById(workItemEvent.getWorkflowInstanceId()).getBizObjectId();
//                log.info("############bizObjectId::{}",bizObjectId);
//                int update = JdbcTemplateUtils.builder(ModelConst.T_GOODS_PURCHASE).putFieldAndVal("client_purchase_request", commentContent)
//                        .eq("id", bizObjectId)
//                        .update();
//            }

        }

        if(EventType.WORKITEM_REJECTED == eventType) {
            FlowActivityEventImpl workItemEvent = (FlowActivityEventImpl) workflowEvent;
//            WorkItemEventImpl workItemEvent = (WorkItemEventImpl) workflowEvent;
            log.info("####################################################");
            log.info("####### 13. 任务驳回后,活动code：{}",workItemEvent.getActivityCode());
        }
    }

//    public BigDecimal getPretaxPrice(BigDecimal pretax_price,BigDecimal num,BigDecimal taxRate,BigDecimal taxRateFreight,BigDecimal pretaxFreight){
//
//    }
}
